import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Box, TableContainer, Stack, Button } from '@material-ui/core';
import { DataGrid, GridColDef, GridRowId } from '@mui/x-data-grid';
import { ToolBar } from '@/pages/credit-transfer/tool-bar';
import { TableTabs } from '@/pages/credit-transfer/table-tabs';
import { RowSelectBar } from '@/pages/credit-transfer/row-select-bar';
import { Detail } from '@/pages/credit-transfer/detail';
import { getMortgageList, getMortgageListStatus } from '@/apis';
import { useRequest } from '@umijs/hooks';

type DataSource = Record<string, any>;
export interface ToolBarProps {
  fetch: (params: any) => void;
  status?: number;
  setStatus?: React.Dispatch<React.SetStateAction<number | undefined>>;
  statusInfo?: Record<string, any>;
  rowSelectedKeys?: GridRowId[];
}

const columns: GridColDef[] = [
  { field: 'assertNo', headerName: '资产编号', width: 200 },
  { field: 'statusDesc', headerName: '审批状态', width: 200 },
  {
    field: 'productName',
    headerName: '融资产品',
    width: 200,
  },
  {
    field: 'amount',
    headerName: '付款金额',
    width: 200,
  },
  {
    field: 'loanAmount',
    headerName: '提前回款金额',
    width: 200,
  },
  {
    field: 'fee',
    headerName: '提前回款利息',
    width: 200,
  },
  {
    field: 'companyName',
    headerName: '供应商',
    width: 200,
  },
  {
    field: 'purchaserName',
    headerName: '购方名称',
    width: 200,
  },
  {
    field: 'fundName',
    headerName: '资金方',
    width: 200,
  },
  {
    field: 'applyTime',
    headerName: '申请时间',
    width: 200,
  },
  {
    field: 'applyBy',
    headerName: '申请人',
    width: 150,
  },
  {
    field: 'approvalTime',
    headerName: '审批时间',
    width: 200,
    renderCell(params) {
      return params.row.approvalTime || '--';
    },
  },
  {
    field: 'approvalBy',
    headerName: '审批人',
    width: 150,
    renderCell(params) {
      return params.row.approvalBy || '--';
    },
  },
  {
    field: 'operate',
    headerName: '操作',
    align: 'center',
    width: 200,
    renderCell(params) {
      return <Detail params={params} />;
    },
  },
];

const useDataSource = ({ dataSource }: { dataSource: DataSource[] }) => {
  return useMemo(() => {
    if (!dataSource?.length) return [];

    return dataSource.map((ret, index) => {
      ret.id = index;

      return ret;
    });
  }, [dataSource]);
};

const RenderToolBars = ({
  fetch,
  setStatus,
  statusInfo,
  rowSelectedKeys,
  status,
}: ToolBarProps) => {
  return (
    <React.Fragment>
      <RowSelectBar
        statusInfo={statusInfo}
        rowSelectedKeys={rowSelectedKeys}
        status={status}
      />
      <TableTabs statusInfo={statusInfo} fetch={fetch} setStatus={setStatus} />
      <ToolBar fetch={fetch} />
    </React.Fragment>
  );
};

export const DataTable = () => {
  const [currentPage, setCurrentPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [status, setStatus] = useState(1);
  const [rowSelectedKeys, setRowSelectedKeys] = useState<GridRowId[]>([]);

  const { data, run, loading } = useRequest(getMortgageList, {
    manual: true,
  });
  const {
    data: statusData,
    run: statusRun,
    loading: statusLoading,
  } = useRequest(getMortgageListStatus, {
    manual: true,
  });
  const dataSource = useDataSource({ dataSource: data?.records || [] });

  useEffect(() => {
    run({ status: 1 });
    statusRun({ productCode: 'quickPay' });
  }, []);

  useEffect(() => {
    setPageSize(data?.size);
  }, [data]);

  return (
    <TableContainer sx={{ height: 'calc(100vh - 160px)' }}>
      <DataGrid
        loading={loading}
        rows={dataSource}
        columns={columns}
        page={currentPage}
        pageSize={pageSize}
        rowCount={data?.total || 10}
        rowsPerPageOptions={[10, 20, 50, 100]}
        scrollbarSize={5}
        onSelectionModelChange={(keys) => {
          setRowSelectedKeys(keys);
        }}
        onPageChange={(page) => {
          run({ current: page + 1 });
          setCurrentPage(page);
        }}
        onPageSizeChange={(pageSize) => {
          run({ size: pageSize });
          setPageSize(pageSize);
        }}
        checkboxSelection={status === 1}
        components={{
          Toolbar: RenderToolBars,
        }}
        componentsProps={{
          toolbar: {
            fetch: run,
            setStatus,
            status,
            statusInfo: statusData,
            rowSelectedKeys,
          },
        }}
      />
    </TableContainer>
  );
};
